package com.scc.service.impl;

import com.scc.mapper.MessageMapper;
import com.scc.pojo.Emp;
import com.scc.pojo.Message;
import com.scc.pojo.MessageList;
import com.scc.service.MessageService;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    //mapper
    @Autowired
    private MessageMapper messageMapper;

    //添加消息列表
    @Override
    public void insertMessageList(MessageList messageList) {
        messageMapper.insertMessageList(messageList);
    }

    //获取消息列表
    @Override
    public List<MessageList> getMessageList(Integer fromEmpId) {
        /*
         *消息列表包括我发起的
         * 别人发起我的
         * **/
        //我发起的
        List<MessageList> myMessageList = messageMapper.selectMyMessageList(fromEmpId);
        //别人发起的
        List<MessageList> otherMessageList = messageMapper.selectOtherMessageList(fromEmpId);
        //汇总的消息列表集合
        ///我发起的消息集合全部添加
        List<MessageList> messageList = new ArrayList<>(myMessageList);
        ///别人的集合遍历不为0就添加
        for (MessageList messagelist : otherMessageList) {
            if(messagelist.getMessageNumber()!=0){
                messageList.add(messagelist);
            }
        }
        //返回汇总的集合
        return messageList;
    }

    //与此同时，要保存当前员工发送的消息
    @Override
    public void insertMessage(Message msg) {
        //保存消息
        messageMapper.insertMessage(msg);
        //对应messageList消息数量要加一
        messageMapper.addMessageNumberById(msg.getMessageId());
    }

    //获取历史聊天记录根据消息的id标记
    @Override
    public List<Message> getHistoryMessage(Integer id) {
        List<Message> messages = messageMapper.getHistoryMessageByMessageId(id);
        //遍历集合获取fromEmpId和toEmp对应的图片,设置变量
        for (Message message : messages) {
            //查两次，返回一个员工对象
            //这是查fromEmpId的
            Emp fromEmp = messageMapper.selectEmpByFromEmpId(message.getFromEmpId());
            //查toEmpId的
            Emp toEmp = messageMapper.selectEmpByToEmpId(message.getToEmpId());
            //设置message对象的照片属性
            message.setFromEmpImage(fromEmp.getImage());
            message.setToEmpImage(toEmp.getImage());
        }
        return messages;
    }

    //删除聊天记录
    @Override
    public void deleteMessageList(Integer id) {
        messageMapper.deleteMessageList(id);
        //聊天数量清空
        messageMapper.updateMessageNumber(id);
    }
}
